//
//  SellHouseEntrustViewController.m
//  House
//
//  Created by 张垚 on 16/6/24.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "SellHouseEntrustViewController.h"
#import "MoveHousePushTableViewCell.h"
#import "ReuseCategoryChooseTableViewCell.h"
#import "ReuseRandomCodeTableViewCell.h"
#import "RentHouseRoomFillTableViewCell.h"
#import "LabelAndTextFieldView.h"
#import "BaseTitleNavigationBar.h"
#import "EntrustLocationViewController.h"
#import "EntrustHouseTypeViewController.h"
#import "MoveHouseAreaChooseViewController.h"
#import "ReuseDescriptionChooseCollectionViewCell.h"
#import "House-Swift.h"
@interface SellHouseEntrustViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
//上传表单专用成员变量
{
    NSString *_housename;
    NSString *_address;
    NSString *_areaid;
    NSString *_lou;
    NSString *_danyuan;
    NSString *_fangjian;
    NSString *_room;
    NSString *_houseearm;
    NSString *_shiyongmj;
    NSString *_price;
    NSString *_truename;
    NSString *_sex;
    NSString *_telephone;
    NSString *_number;
    NSString *_mendian;
    NSString *_area;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UICollectionView *imageCollectionView;
@property (nonatomic, strong) UIButton *submitButton;
@property (nonatomic, strong) NSMutableArray *descriptionArr;
@property (nonatomic, strong) NSMutableArray *placeHolderArr;

@property (nonatomic, strong) NSMutableDictionary *submitInfoDic;
@property (nonatomic, assign) CGFloat kbHeight;

@property (nonatomic, strong) BaseTitleNavigationBar *myBar;
@property (nonatomic, strong) MBProgressHUD *hud;

@property (nonatomic, strong) NSMutableArray<UIImage *> *cellImageArr;
@property (nonatomic, strong) NSMutableArray<UIImage *> *submitImageArr;
@property (nonatomic, strong) NSMutableArray *downloadPicArray;
@property (nonatomic, copy) NSArray *dataArray;//暂存array
@property (nonatomic, strong) NSMutableArray *titleArray;

@end

@implementation SellHouseEntrustViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
     self.automaticallyAdjustsScrollViewInsets = NO;
    _cellImageArr = @[[UIImage imageNamed: @"submitPhoto"]].mutableCopy;
    //默认的手机号
    _telephone = [UserInfoManager sharedManager].phoneNumber;
    _sex = @"0";
    /* 默认键盘高度 */
    _kbHeight = 258.0f;
    /* 提交数据的字典 */
    _submitInfoDic = [NSMutableDictionary dictionary];
    /* 数据 */
    if (_model) {
        self.titleArray = @[@[_model.areaname, _model.street, _model.housename].mutableCopy, @[@"", _model.room, _model.houseearm, _model.shiyongmj, _model.price, _model.company, _model.truename, _model.sex, _model.telephone].mutableCopy].mutableCopy;
        _housename = _model.housename;
        _address = _model.address;
        _areaid = _model.areaid;
        _lou = _model.lou;
        _danyuan = _model.danyuan;
        _fangjian = _model.fangjian;
        _room = _model.room;
        _houseearm = _model.houseearm;
        _shiyongmj = _model.shiyongmj;
        _price = _model.price;
        _truename = _model.truename;
        _sex = _model.sex;
        _telephone = _model.telephone;
        _number = _model.number;
        _mendian = _model.mendian;
        [self downloadPic];

    } else {
        _placeHolderArr = @[@"请选择区域", @"请输入街道", @"请输入小区名称", @"", @"请选择户型", @"请输入建筑面积", @"请输入使用面积", @"请输入售价", @"请选择门店", @"请输入您的姓名", @"请输入您的性别", @"请输入手机号"].mutableCopy;
    }
    _descriptionArr = @[@"区域", @"街道", @"小区名称", @"门牌号", @"户型", @"建筑面积", @"使用面积", @"售价", @"门店", @"姓名", @"性别", @"手机号"].mutableCopy;

    [self initTableView];
    [self initNavigationBar];
    /* 添加观察者 */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:@"infoNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    // Do any additional setup after loading the view.
}
- (void)downloadPic {
    [NetRequest getInformationWithGetMethodWithUrl:[NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/api.php/Index/App_tuku/id/%@/mid/5", _model.itemid] success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@", responseObject);
        if ([responseObject isKindOfClass:[NSArray class]]) {
            _downloadPicArray = responseObject;
            [_cellImageArr removeAllObjects];
            for (NSDictionary *dic in responseObject) {
                [NetRequest downLoadImageWithUrl:dic[@"thumb"] withBlock:^(UIImage *image) {
                    [_cellImageArr addObject:image];
                    //                    [_tableView reloadData];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [_imageCollectionView reloadData];
                    });

                }];
            }
            _dataArray = _cellImageArr.copy;
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}
- (void)notification:(NSNotification *)notification {
    
}
#pragma mark - 顶部视图 返回上一层级
- (void)initNavigationBar {
    _myBar = [[BaseTitleNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64) WithTitleStr:@"卖房委托"];
    [self.view addSubview:_myBar];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)];
    [_myBar.leftView addGestureRecognizer:tap];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 键盘监听事件
- (void)keyboardWillShow:(NSNotification *)showNotification {
    /*获取键盘高度 中英文下高度是不同的 */
    CGFloat kbHeight = [[showNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    /* 将高度赋给属性 */
    _kbHeight = kbHeight;
    
}
- (void)keyboardWillHide:(NSNotification *)hideNotification {
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[hideNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _tableView.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64);
    }];
}
#pragma mark - 提交表单
/* 提交信息 */
- (void)submit:(UIButton *)button {
    if (_areaid.length == 0) {
        [self alertMessage:@"请选择区域"];
    }else if (_address.length == 0) {
        [self alertMessage:@"请输入街道"];
    }else if (_housename.length == 0) {
        [self alertMessage:@"请输入小区名称"];
    }else if (_lou.length == 0) {
        [self alertMessage:@"请输入楼号"];
    }else if (_danyuan.length == 0) {
        [self alertMessage:@"请输入单元号"];
    }else if (_fangjian.length == 0) {
        [self alertMessage:@"请输入房间号"];
    }else if (_room.length == 0) {
        [self alertMessage:@"请选择户型"];
    }else if (_houseearm.length == 0) {
        [self alertMessage:@"请输入建筑面积"];
    }else if (_shiyongmj.length == 0) {
        [self alertMessage:@"请输入使用面积"];
    }else if (_price.length == 0) {
        [self alertMessage:@"请输入售价"];
    }else if (_mendian.length == 0) {
        [self alertMessage:@"请选择门店"];
    }
    else if (_truename.length == 0) {
        [self alertMessage:@"请输入姓名"];
    }else if ([_sex isEqualToString:@"0"]) {
        [self alertMessage:@"请选择性别"];
    }else {
        if (![self valiMobile:_telephone]) {
                NSMutableDictionary *submitInfoDic = [NSMutableDictionary dictionary];
                [submitInfoDic setObject:@"save" forKey:@"dir"];
                [submitInfoDic setObject:[UserInfoManager sharedManager].uid forKey:@"userid"];
            
                [submitInfoDic setObject:_areaid forKey:@"areaid"];
                [submitInfoDic setObject:_address forKey:@"address"];
                [submitInfoDic setObject:_housename forKey:@"housename"];
                [submitInfoDic setObject:_lou forKey:@"lou"];
                [submitInfoDic setObject:_danyuan forKey:@"danyuan"];
                [submitInfoDic setObject:_fangjian forKey:@"fangjian"];
                [submitInfoDic setObject:_room forKey:@"room"];
                [submitInfoDic setObject:_houseearm forKey:@"houseearm"];
                [submitInfoDic setObject:_shiyongmj forKey:@"shiyongmj"];
                [submitInfoDic setObject:_mendian forKey:@"mendian"];
                [submitInfoDic setObject:_price forKey:@"price"];
            
                [submitInfoDic setObject:_truename forKey:@"truename"];
                [submitInfoDic setObject:_sex forKey:@"sex"];
                [submitInfoDic setObject:_telephone forKey:@"telephone"];

            if (_model) {
                if (_cellImageArr.count == 1 && [_cellImageArr.firstObject isEqual:[UIImage imageNamed: @"submitPhoto"]]) {
                    [self alertMessage:@"至少上传一张图片"];
                    return;
                } else {
                    if (_dataArray.hash == _cellImageArr.hash) {
                        _submitImageArr = @[].mutableCopy;
                    } else {
                        _submitImageArr = [NSMutableArray arrayWithArray:_cellImageArr];
                        [_submitImageArr removeLastObject];
                    }
                }
            } else {
                if (_cellImageArr.count == 1 ) {
                    [self alertMessage:@"至少上传一张图片"];
                    return;
                }else {
                    _submitImageArr = [NSMutableArray arrayWithArray:_cellImageArr];
                    if (_cellImageArr.count == 6) {

                    }else {
                        [_submitImageArr removeLastObject];
                    }
                }
            }
            if (_submitImageArr.count != 0) {
                [submitInfoDic setObject:[NSString stringWithFormat:@"%ld", (long)_submitImageArr.count] forKey:@"number"];
            }

            for (int i = 1; i <= _submitImageArr.count; i++) {
                [submitInfoDic setObject:[NSString stringWithFormat:@"file%d.jpg", arc4random()%100000]  forKey:[NSString stringWithFormat:@"target_file%d", i]];
            }
            _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                _hud.label.text = @"正在上传";
            NSString *url;
            if (_model) {
                [submitInfoDic setObject:_model.itemid forKey:@"id"];
                url = @"http://aizufang.hrbzjwl.com/tp/api.php/Index/App_edit_maifang";
            } else {
                url = @"http://aizufang.hrbzjwl.com/tp/api.php/Index/App_maifangweituo";
            }
                [NetRequest upLoadEntrustImageArr:_submitImageArr withUrl:url withParameters:submitInfoDic progress:^(NSProgress *progress) {
                } success:^(NSURLSessionDataTask *task, id responseObject) {
                    if ([[responseObject[@"flg"] description] isEqualToString:@"1"]) {
                        _hud.label.text = @"上传成功";
                        [_hud hideAnimated:YES afterDelay:1];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self back];
                        });
                    }else {
                        _hud.label.text = @"上传失败";
                        [_hud hideAnimated:YES afterDelay:1];
                    }
                    
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    _hud.label.text = @"服务器错误";
                    [_hud hideAnimated:YES afterDelay:1];
                }];

}else {
            [self alertMessage:[self valiMobile:_telephone]];
        }
}
    
}
//手机号判断
- (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return @"请输入11位手机号";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        }else{
            return @"请输入正确格式的手机号";
        }
    }
    return nil;
}
//提交表单不完整的提示信息
- (void)alertMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:nil];
    });
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark - tableview

/* 创建tableView */
- (void)initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStyleGrouped];
    _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[MoveHousePushTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MoveHousePushTableViewCell class])];
    [_tableView registerClass:[ReuseCategoryChooseTableViewCell class] forCellReuseIdentifier:NSStringFromClass([ReuseCategoryChooseTableViewCell class])];
    [_tableView registerClass:[RentHouseRoomFillTableViewCell class] forCellReuseIdentifier:NSStringFromClass([RentHouseRoomFillTableViewCell class])];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    footerView.backgroundColor = [UIColor whiteColor];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(80, 100);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _imageCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    [footerView addSubview:_imageCollectionView];
    _imageCollectionView.backgroundColor = [UIColor whiteColor];
    _imageCollectionView.delegate = self;
    _imageCollectionView.dataSource = self;
    _imageCollectionView.bounces = NO;
    _imageCollectionView.showsHorizontalScrollIndicator = NO;
    [_imageCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footerView.mas_left).offset(10);
        make.right.equalTo(footerView.mas_right).offset(-10);
        make.height.equalTo(@100);
        make.top.equalTo(footerView.mas_top).offset(10);
    }];
    [_imageCollectionView registerClass:[ReuseDescriptionChooseCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([ReuseDescriptionChooseCollectionViewCell class])];
    
    _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [footerView addSubview:_submitButton];
    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_imageCollectionView.mas_bottom).offset(20);
        make.left.equalTo(footerView.mas_left).offset(40);
        make.right.equalTo(footerView.mas_right).offset(-40);
        make.height.equalTo(@50);
    }];
    _submitButton.layer.masksToBounds = YES;
    _submitButton.layer.cornerRadius = 6;
    [_submitButton setTitle:@"提交" forState:UIControlStateNormal];
    [_submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _submitButton.backgroundColor = [UIColor colorWithRed:212 / 255.0f green:38 / 255.0f blue:26 / 255.0f alpha:1.0];
    [_submitButton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    _tableView.tableFooterView = footerView;
        
}

/* 分区数 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
/* Footer高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
/* Header高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGFLOAT_MIN;
    }else {
        return 20;
    }
}
/* 分区中的行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }else {
        return 9;
    }
}
/* cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        //门牌号
        if (indexPath.row == 0) {
            RentHouseRoomFillTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([RentHouseRoomFillTableViewCell class])];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.roomView.buildingNumTextfield.delegate = self;
            cell.roomView.unitNumTextfiled.delegate = self;
            cell.roomView.roomNumTextField.delegate = self;
            if (_model) {
                cell.roomView.buildingNumTextfield.text = _model.lou;
                cell.roomView.unitNumTextfiled.text = _model.danyuan;
                cell.roomView.roomNumTextField.text = _model.fangjian;
            }
            cell.descriptionLabel.text = _descriptionArr[indexPath.section * 3 + indexPath.row];
            return cell;
        }else {
            MoveHousePushTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MoveHousePushTableViewCell class])];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.inputView.titleLabel.text = _descriptionArr[indexPath.section * 3 + indexPath.row];
            cell.inputView.contextTextField.tag = indexPath.section * 3+ indexPath.row;
            if (_model) {
                cell.inputView.contextTextField.text = _titleArray[indexPath.section][indexPath.row];
            }
            if (indexPath.row == 1 || indexPath.row == 5 || indexPath.row == 7) {
                cell.inputView.contextTextField.userInteractionEnabled = NO;
                cell.isPush = YES;
                cell.inputView.contextTextField.placeholder = _placeHolderArr[indexPath.section * 3 + indexPath.row];
                if (indexPath.row == 7) {
                    if ([_sex isEqualToString:@"0"]) {
                        cell.inputView.contextTextField.placeholder = _placeHolderArr[indexPath.section * 3 + indexPath.row];
                    }else if ([_sex isEqualToString:@"1"]) {
                        cell.inputView.contextTextField.text = @"男";
                    }else {
                        cell.inputView.contextTextField.text = @"女";
                    }
                }
            }else {
                cell.inputView.contextTextField.delegate = self;
                cell.isPush = NO;
                if (indexPath.row == 8) {
                    cell.inputView.contextTextField.text = _telephone;
                }else {
                    cell.inputView.contextTextField.placeholder = _placeHolderArr[indexPath.section * 3 + indexPath.row];
                }
            }
            return cell;
        }
    } else {
        NSString *cellID = [NSString stringWithFormat:@"cell%ld%ld", (long)indexPath.section,(long)indexPath.row];
        MoveHousePushTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[MoveHousePushTableViewCell alloc] init];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {
            cell.inputView.contextTextField.userInteractionEnabled = NO;
            if (_area.length == 0) {
               cell.inputView.contextTextField.placeholder = _placeHolderArr[indexPath.row];
            }else {
                cell.inputView.contextTextField.text = _area;
            }
        }else {
            if (indexPath.row == 1) {
                if (_address.length == 0) {
                   cell.inputView.contextTextField.placeholder = _placeHolderArr[indexPath.row];
                }else {
                    cell.inputView.contextTextField.text = _address;
                }
            }else {
                if (_housename.length == 0) {
                    cell.inputView.contextTextField.placeholder = _placeHolderArr[indexPath.row];
                }else {
                    cell.inputView.contextTextField.text = _housename;
                }
            }
            cell.isPush = NO;
            cell.inputView.contextTextField.delegate = self;
            cell.inputView.contextTextField.tag = indexPath.row;
        }
        cell.inputView.titleLabel.text = _descriptionArr[indexPath.row];
        if (_model) {
            cell.inputView.contextTextField.text = _titleArray[indexPath.section][indexPath.row];
        }
        return cell;
    }
}
//cell点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MoveHousePushTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            MoveHouseAreaChooseViewController *areaChooseVC = [[MoveHouseAreaChooseViewController alloc] init];
            areaChooseVC.categoryStr = @"区域选择";
            areaChooseVC.currentStr = cell.inputView.contextTextField.text;
            [areaChooseVC passInfoToPreviousPage:^(NSString *infoStr, NSInteger tag) {
                cell.inputView.contextTextField.text = infoStr;
                _areaid = [NSString stringWithFormat:@"%ld", (long)tag];
                _area = infoStr;
                if (_model) {
                    [_titleArray[indexPath.section] replaceObjectAtIndex:indexPath.row withObject:infoStr];
                }
            }];
            [self.navigationController pushViewController:areaChooseVC animated:YES];
        }
    }else {
        if (indexPath.row == 1) {
            EntrustHouseTypeViewController *entrustVC = [[EntrustHouseTypeViewController alloc] init];
            entrustVC.currentStr = cell.inputView.contextTextField.text;
            entrustVC.tag = 1;
            [entrustVC passInfoToPreviousPage:^(NSString *currentStr, NSInteger currentTag) {
                cell.inputView.contextTextField.text = currentStr;
                _room = [NSString stringWithFormat:@"%ld", (long)currentTag];
                if (_model) {
                    [_titleArray[indexPath.section] replaceObjectAtIndex:indexPath.row withObject:currentStr];
                }
            }];
            [self.navigationController pushViewController:entrustVC animated:YES];
        }else if (indexPath.row == 5) {
            if (_areaid.length == 0) {
                [self alertMessage:@"请先选择区域"];
            }else {
                EntrustHouseTypeViewController *entrustVC = [[EntrustHouseTypeViewController alloc] init];
                entrustVC.tag = 3;
                entrustVC.currentStr = cell.inputView.contextTextField.text;
                entrustVC.areaID = _areaid;
                [entrustVC passInfoToPreviousPage:^(NSString *currentStr, NSInteger currentTag) {
                    cell.inputView.contextTextField.text = currentStr;
                    _mendian = [NSString stringWithFormat:@"%ld", (long)currentTag];
                    if (_model) {
                        [_titleArray[indexPath.section] replaceObjectAtIndex:indexPath.row withObject:currentStr];
                    }
                }];
                [self.navigationController pushViewController:entrustVC animated:YES];
            }
        }
        else if (indexPath.row == 7) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction *manAction = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                cell.inputView.contextTextField.text = @"男";
                _sex = @"1";
            }];
            UIAlertAction *womanAction = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                cell.inputView.contextTextField.text = @"女";
                _sex = @"2";
            }];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:manAction];
            [alertController addAction:womanAction];
            [alertController addAction:cancel];
            [self presentViewController:alertController animated:YES completion:nil];
        }
    }
    
}
#pragma mark - 代理协议
/* 点击return 键盘回落 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
/* 编辑完成 监听textfiled上的字段 */
- (void)textFieldDidEndEditing:(UITextField *)textField {
    //根据标签 给对应的成员变量赋值
    if (textField.tag == 1) {
        _address = textField.text;
        if (_model) {
            [_titleArray[0] replaceObjectAtIndex:1 withObject:_address];
        }
    }else if (textField.tag == 2) {
        _housename = textField.text;
        if (_model) {
            [_titleArray[0] replaceObjectAtIndex:2 withObject:_housename];
        }
    }else if (textField.tag == 100) {
        _lou = textField.text;
        if (_model) {
            _model.lou = _lou;
        }
    }else if (textField.tag == 101) {
        _danyuan = textField.text;
        if (_model) {
            _model.danyuan = _danyuan;
        }
    }else if (textField.tag == 102) {
        _fangjian = textField.text;
        if (_model) {
            _model.fangjian = _fangjian;
        }
    }else if (textField.tag == 5) {
        _houseearm = textField.text;
        if (_model) {
            [_titleArray[1] replaceObjectAtIndex:2 withObject:_houseearm];
        }
    }else if (textField.tag == 6) {
        _shiyongmj = textField.text;
        if (_model) {
            [_titleArray[1] replaceObjectAtIndex:3 withObject:_shiyongmj];
        }
    }else if (textField.tag == 7) {
        _price = textField.text;
        if (_model) {
            [_titleArray[1] replaceObjectAtIndex:4 withObject:_price];
        }
    }else if (textField.tag == 9) {
        _truename = textField.text;
        if (_model) {
            [_titleArray[1] replaceObjectAtIndex:6 withObject:_truename];
        }
    }else if (textField.tag == 11) {
        _telephone = textField.text;
        if (_model) {
            [_titleArray[1] replaceObjectAtIndex:8 withObject:_telephone];
        }
    }
}
/* 即将开始编辑 键盘弹起 视图上移 */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIView *view = textField.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    CGRect rect = [cell convertRect:cell.frame toView:self.view];
    if (rect.origin.y / 2 + rect.size.height >= self.view.frame.size.height - _kbHeight) {
        CGFloat offset = _kbHeight;
        [UIView animateWithDuration:0.25 animations:^{
            _tableView.frame = CGRectMake(0, -offset + 64, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
    return YES;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _cellImageArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ReuseDescriptionChooseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ReuseDescriptionChooseCollectionViewCell class]) forIndexPath:indexPath];
    cell.descriptionImageView.image = _cellImageArr[indexPath.item];
    cell.block = ^(UILongPressGestureRecognizer *longPress){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"删除所有图片" message:@"注意:此操作不可恢复" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self deleteAllPhotos];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:okAction];
        [alertController addAction:cancel];
        [self presentViewController:alertController animated:YES completion:nil];
    };
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ReuseDescriptionChooseCollectionViewCell *cell = (ReuseDescriptionChooseCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (![cell.descriptionImageView.image isEqual:[UIImage imageNamed:@"submitPhoto"]]) {
        
    }else {
        [self cellClickAction];
    }
    
}
//点击添加照片cell 调取图库或相机
- (void)cellClickAction {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectForCameraButtonClick];
    }];
    UIAlertAction *pictrueAction = [UIAlertAction actionWithTitle:@"从相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectForAlbumButtonClick];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cameraAction];
    [alertController addAction:pictrueAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

//访问相册
-(void)selectForAlbumButtonClick
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"访问图片错误" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }
}

//访问摄像头
-(void)selectForCameraButtonClick
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"访问图片错误" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }
}

- (void)deleteAllPhotos {
    if (_downloadPicArray) {
        for (NSDictionary *dic in _downloadPicArray) {
            [NetRequest getInformationWithGetMethodWithUrl:[NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/api.php/Index/App_delphoto/id/%@", dic[@"itemid"]] success:^(NSURLSessionDataTask *task, id responseObject) {

            } failure:^(NSURLSessionDataTask *task, NSError *error) {

            }];
        }
        [_cellImageArr removeAllObjects];
        [_cellImageArr addObject:[UIImage imageNamed: @"submitPhoto"]];

    } else {
        [_cellImageArr removeAllObjects];
        [_cellImageArr addObject:[UIImage imageNamed: @"submitPhoto"]];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [_imageCollectionView reloadData];
    });
}
//图像选取器的委托方法，选完图片后回调该方法

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [_cellImageArr insertObject:info[UIImagePickerControllerOriginalImage] atIndex:0];
    if (_cellImageArr.count >= 7) {
        [_cellImageArr removeLastObject];
    }
    [_imageCollectionView reloadData];
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}





#pragma mark - 移除观察者
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
